package com.sangmo.fts.process.storage.calculator;

import com.sangmo.boot.framework.common.utils.ApplicationUtils;
import com.sangmo.boot.framework.data.json.context.KeyValue;
import com.sangmo.boot.framework.data.json.load.Calculator;
import com.sangmo.fts.basic.model.Goods;
import com.sangmo.fts.basic.service.GoodsService;
import com.sangmo.fts.process.storage.model.CsfContract;
import com.sangmo.fts.process.storage.model.CsfContractItem;
import com.sangmo.fts.process.storage.repo.CsfContractItemRepo;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
public class CsfContractAmountCalculator implements Calculator<CsfContract>, CsfContract.ICsfContractAmountCalculator {

    @Override
    public Object calc(CsfContract bean, Collection<KeyValue> exts) {
        CsfContractItemRepo csfContractItemRepo = ApplicationUtils.getBean(CsfContractItemRepo.class);
        List<CsfContractItem> contractItems = csfContractItemRepo.findByContractId(bean.getId());
        GoodsService goodsService = ApplicationUtils.getBean(GoodsService.class);
        Map<Long, Goods> goodsMap = goodsService.getAllGoodsMapCache();
        BigDecimal contractAmount = BigDecimal.ZERO;
        for (CsfContractItem item : contractItems) {
            Goods goods = goodsMap.get(item.getGoodsId());
            BigDecimal price = (goods == null?BigDecimal.ZERO :goods.getPrice());
            contractAmount = contractAmount.add(price.multiply(item.getQuantity()));
        }
        return contractAmount;
    }
}
